//
//  UserSingleton.m
//  UI_豆瓣项目
//
//  Created by dllo on 15/11/5.
//  Copyright (c) 2015年 关业达. All rights reserved.
//

#import "UserSingleton.h"
#import <sqlite3.h>

@implementation UserSingleton

+ (instancetype)shareSingleton
{
    static UserSingleton *userSingleton = nil;
    if (userSingleton == nil) {
        userSingleton = [[UserSingleton alloc] init];
        
    }
    return userSingleton;
}

// 声明数据库
static sqlite3 *ub = nil;

// 打开数据库
- (void)openUB{
    if (ub != nil) {
        NSLog(@"数据库已经打开");
        return;
    }
    NSString *sqlFile = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *sqlPath = [sqlFile stringByAppendingPathComponent:@"user.sqlite"];
    BOOL result = sqlite3_open(sqlPath.UTF8String, &ub);
    if (result == SQLITE_OK ) {
        NSLog( @"打开成功");
        NSLog(@"sqlPath = %@",sqlPath);
    }else{
        NSLog(@"打开失败");
    }
}

// 创建表
- (void)createTable{
    NSString *sql = @"CREATE TABLE IF NOT EXISTS user111(number INTEGER PRIMARY KEY AUTOINCREMENT, uname TEXT, code TEXT)";
    BOOL result = sqlite3_exec(ub, sql.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"创建表成功");
    }
}

// 插入一个用户
- (void)insertUser:(UserLogin *)userLogin
{
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO user123(uname, code) VALUES('%@', '%@')", userLogin.uname, userLogin.code];
    NSLog(@"00000000%@", userLogin);
    BOOL result =  sqlite3_exec(ub, sql.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"插入成功");
    }
    else {
        NSLog(@"插入失败");
    }
}


// 查询用户
- (NSMutableArray *)selectUser:(NSString *)name
{
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM user123 WHERE uname = '%@'", name];
    sqlite3_stmt *stmt = nil;
    BOOL result = sqlite3_prepare(ub, sql.UTF8String, -1, &stmt, nil);
    if (result == SQLITE_OK) {
        NSLog(@"查询准备成功");
    }else{
        NSLog(@"查询准备失败");
    }
    //循环遍历每一行数据
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        
        // 取出第二列数据
        const unsigned char *uname = sqlite3_column_text(stmt, 1);
        const unsigned char *code = sqlite3_column_text(stmt, 2);
        NSString *nameSter = [NSString stringWithUTF8String:(const char *)uname];
        NSString *codeSter = [NSString stringWithUTF8String:(const char *)code];
        
        UserLogin *userLogin = [[UserLogin alloc] init];
        userLogin.uname = nameSter;
        userLogin.code = codeSter;
        [array addObject:userLogin];
        
}
    NSLog(@"array>>>>>>>>%@", array);
    return array;
}




@end
